<template>
	<view v-if="svgStyle" class="svg" :style="svgStyle" />
</template>

<script setup>
	import {
		ref,
		watch
	} from "vue";

	const props = defineProps({
		src: String,
		colors: Array,
		replaceExp: {
			type: RegExp,
			default: /#E5E5E5/g,
		}
	});

	const svgStyle = ref(null);
	const {
		src,
		colors,
		replaceExp,
	} = props;
	watch(props, (props) => {
		if(props.src !== src || props.colors !== colors) {
			readSvg(props.src, props.colors)
		}
	})
	const readSvg = (src, colors) => {
		// 读取 src 链接资源
		uni.getFileSystemManager().readFile({
			filePath: src,
			encoding: 'binary',
			success: res => {
				let basestr
				if (colors && colors.length) {
					let a = 0
					// 匹配 Hex 数值，并进行替换
					basestr = res.data.replace(replaceExp, (word) => {
						const newColor = colors[a]
						a = a + 1
						return newColor ? newColor : word
					})
					// console.log('替换后的basestr', basestr)
				} else {
					basestr = res.data
				}
				// 将 svg 数据进行 URL 编码
				basestr = encodeURIComponent(basestr)
				svgStyle.value = `background-image: url("data:image/svg+xml,${basestr}");`
			}
		})
	}
	readSvg(src, colors);
</script>

<style lang="less" scoped>
	.svg {
		background-repeat: no-repeat;
		background-size: contain;
		width: 100%;
		height: 100%;
	}
</style>